package com.zcxx.cotton.sale.task;


import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.config.ApiConfig;
import com.ruoyi.common.config.TaskConfig;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.http.HttpClientUtils;
import com.ruoyi.common.utils.http.SendUtils;
import com.ruoyi.system.mapper.SysDeptMapper;
import com.ruoyi.system.service.ISysDeptService;
import com.zcxx.cotton.base.domain.PubDevice;
import com.zcxx.cotton.base.service.IPubDeviceService;
import com.zcxx.cotton.pick.domain.PickInfo;
import com.zcxx.cotton.pick.service.IPickInfoService;
import com.zcxx.cotton.sale.domain.BuySaleinfosSample;
import com.zcxx.cotton.sale.domain.BuySaleinfosSub;
import com.zcxx.cotton.sale.domain.BuySubsidyRecords;
import com.zcxx.cotton.sale.domain.SaleInfo;
import com.zcxx.cotton.sale.service.IBuySaleinfosSampleService;
import com.zcxx.cotton.sale.service.IBuySaleinfosSubService;
import com.zcxx.cotton.sale.service.IBuySubsidyRecordsService;
import com.zcxx.cotton.sale.service.ISaleInfoService;
import com.zcxx.cotton.sale.utils.CottonSubsidyConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.text.SimpleDateFormat;
import java.time.Year;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 吴璇璇
 * @title: SaleTask
 * @projectName ruoyi
 * @description: TODO
 * @date 2025/7/28 16:19
 */

@Component("SaleTask")
public class SaleTask {

    @Autowired
    private ISaleInfoService saleInfoService;

    @Autowired
    private IBuySaleinfosSampleService buySaleinfosSampleService;

    @Autowired
    private IBuySaleinfosSubService buySaleinfosSubService;

    @Autowired
    private ApiConfig apiConfig;

    @Autowired
    private SendUtils sendUtils;

    @Autowired
    private IPickInfoService pickInfoService;

    @Autowired
    private ISysDeptService  sysDeptService;

    @Autowired
    private SysDeptMapper  sysDeptMapper;

    @Autowired
    private IPubDeviceService pubDeviceService;

    @Autowired
    private IBuySubsidyRecordsService buySubsidyRecordsService;
    /**
     * 每1分钟执行一次,1.5.8从平台获取部门列表信息接口(获取firmCode用于调下一个从接口获取交售信息和籽棉交售棉包信息）
     * 先从利华这个大部门把加工厂的部门编码拉过来(sys_dept)
     * 获取加工厂编码(每隔10分钟执行一次：0 0/10 * * * ?)
     */
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void getDeptList() {
        if (!TaskConfig.isFlag()) {
            return;
        }
        String URL = apiConfig.getUrl() + "/api/getDeptList";
        JSONObject object = new JSONObject();
        object.put("parentId", apiConfig.getDeptId());
        String s = sendUtils.sendPost(URL, object);
        JSONObject parse = JSONObject.parse(s);
        JSONArray data = parse.getJSONArray("data");
        // JSONArray转List
        List<SysDept> list = data.toJavaList(SysDept.class);
        for (SysDept sysDept : list) {
            //先查询是否存在
            sysDept.setAncestors("0" + "," + sysDept.getParentId());
            SysDept deptById = sysDeptService.selectDeptById(sysDept.getDeptId());
            if (deptById == null) {//新增
                sysDeptService.insertDept(sysDept);
            } else {//修改
                sysDeptService.updateDept(sysDept);
            }
        }
    }


    //然后根据拉过来的加工厂编码去获取下面的龙门架设备(pub_device)(每隔20分钟执行一次：0 0/20 * * * ?)
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void getDeviceList() {
        if (!TaskConfig.isFlag()) {
            return;
        }
        String URL = apiConfig.getUrl() + "/api/getDeviceList";
        //查询加工厂的编码
        List<SysDept> deptList = sysDeptService.selectChildrenDeptById(apiConfig.getDeptId());
        for (SysDept sysDept : deptList) {
            JSONObject object = new JSONObject();
            object.put("deptId", sysDept.getDeptId());
            String s = sendUtils.sendPost(URL, object);
            JSONObject parse = JSONObject.parse(s);
            JSONArray data = parse.getJSONArray("data");
            // JSONArray转List
            List<PubDevice> pubDeviceList = data.toJavaList(PubDevice.class);
            pubDeviceService.saveOrUpdateBatch(pubDeviceList);
        }
    }

    /**
     * 从接口获取交售信息和籽棉交售棉包信息
     */
    //@Scheduled(cron = "0 0/1 * * * ?") //5分钟一次
    public void getSaleInfoByLh() {
        try {
            if (!TaskConfig.isFlag()) {
                return;
            }
            String URL = "https://sgxt.lhcotton.com:3334/hcsgxt-api/sgxt/zm/factory/detail/search_zs";
            Date currentDate = new Date();

            // 创建格式化器
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");

            // 格式化日期
            String formattedDate = formatter.format(currentDate);
            SysDept sysDept1=new SysDept();
            sysDept1.setDeptClass("2");
            //查询加工厂的编码
            List<SysDept> deptList = sysDeptMapper.selectDeptList(sysDept1);
            for (SysDept sysDept : deptList) {
                JSONObject object = new JSONObject();
                object.put("factory_name", sysDept.getDeptName());
                object.put("gross_date", formattedDate);
                String s = HttpClientUtils.doPostJson(URL, object.toJSONString());
                JSONObject parse = JSONObject.parse(s);
                JSONArray data = parse.getJSONArray("data");
                Year year = Year.now();

                for ( Object js :data ) {
                    BuySubsidyRecords buySubsidyRecords = CottonSubsidyConverter.convertFromJson(js.toString());
                    buySubsidyRecords.setYear(year.toString());
                    buySubsidyRecords.setDeptId(sysDept.getDeptId());

                    //保存到交售信息表
                    BuySubsidyRecords buySubsidyRe=buySubsidyRecordsService.selectBuySubsidyRecordsById(buySubsidyRecords.getId());
                    if(buySubsidyRe ==null){
                        buySubsidyRecordsService.insertBuySubsidyRecords(buySubsidyRecords);
                    }else {
                        buySubsidyRecordsService.updateBuySubsidyRecords(buySubsidyRecords);
                    }

                }

            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 从接口获取交售信息和籽棉交售棉包信息
     */
    //@Scheduled(cron = "0 0/1 * * * ?") //5分钟一次
    public void getSaleInfo() {
        try {
            if (!TaskConfig.isFlag()) {
                return;
            }
            String URL = apiConfig.getUrl() + "/api/getSaleInfosList";
            //查询加工厂的编码
            List<SysDept> deptList = sysDeptService.selectChildrenDeptById(apiConfig.getDeptId());
            for (SysDept sysDept : deptList) {
                JSONObject object = new JSONObject();
                object.put("firmCode", sysDept.getDeptCode());
                JSONObject params = new JSONObject();
                params.put("endCreateTime", apiConfig.getEndCreateTime());
                params.put("beginCreateTime", apiConfig.getBeginCreateTime());
                object.put("params", params);
                String s = sendUtils.sendPost(URL, object);
                JSONObject parse = JSONObject.parse(s);
                JSONArray data = parse.getJSONArray("data");
//                System.out.println(data);
                // JSONArray转List
                List<SaleInfo> saleInfoList = data.toJavaList(SaleInfo.class);
                //保存到交售信息表
                saleInfoService.saveOrUpdateBatch(saleInfoList);
                //根据每个billNoWeight调用1.5.5 从平台获取籽棉交售棉包信息列表信息接口(IW001)
                for (SaleInfo saleInfo : saleInfoList) {
                    String URLTwo = apiConfig.getUrl() + "/api/getSaleinfosSampleList";
                    JSONObject objectTwo = new JSONObject();
                    objectTwo.put("billNoWeight", saleInfo.getBillNoWeight());
                    String sTwo = sendUtils.sendPost(URLTwo, objectTwo);
                    JSONObject parseTwo = JSONObject.parse(sTwo);
                    JSONArray listTwo = parseTwo.getJSONArray("data");
                    // JSONArray转List
                    List<BuySaleinfosSample> saleSampleList = listTwo.toJavaList(BuySaleinfosSample.class);
                    buySaleinfosSampleService.saveOrUpdateBatch(saleSampleList);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    /**
     * 根据龙门架设备编码获取龙门架数据(10分钟一次)
     */
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void getSaleinfosSubList() {
        if (!TaskConfig.isFlag()) {
            return;
        }
        try {
            String URL = apiConfig.getUrl() + "/api/getSaleinfosSubList";
            String today = apiConfig.getBeginCreateTime1();
            String beginCreateTime = today + " 00:00:00";
            String endCreateTime = DateUtils.getNextMonth(today) + " 23:59:59";

            // 查询全部龙门架设备
            List<PubDevice> devices = pubDeviceService.list();

            for (PubDevice device : devices) {
                // 构建请求参数
                JSONObject requestBody = new JSONObject();
                requestBody.put("deviceCode", device.getId());

                JSONObject params = new JSONObject();
                params.put("beginCreateTime", beginCreateTime);
                params.put("endCreateTime", endCreateTime);
                requestBody.put("params", params);

                // 发送请求
                String response = sendUtils.sendPost(URL, requestBody);
                JSONObject responseJson = JSONObject.parseObject(response);
                JSONArray dataArray = responseJson.getJSONArray("data");

                if (dataArray == null || dataArray.isEmpty()) {
                    continue;
                }

                // 转换数据
                List<BuySaleinfosSub> saleinfosSubList = dataArray.toJavaList(BuySaleinfosSub.class);
                List<SaleInfo> saleInfoList = convertToSaleInfoList(saleinfosSubList);

                // 批量保存数据
                if (!saleInfoList.isEmpty()) {
                    saleInfoService.saveOrUpdateBatch(saleInfoList);
                }
                if (!saleinfosSubList.isEmpty()) {
                    buySaleinfosSubService.saveOrUpdateBatch(saleinfosSubList);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    // 2分钟一次
    //@Scheduled(cron = "0 0/1 * * * ?")
    public void updateIsSale() {
        if (!TaskConfig.isFlag()) {
            return;
        }
        /** 是否交售 0：未交售  1：已交售 **/
        String isSale="1";
        int result=pickInfoService.updateIsSale(isSale);
        System.out.println("更新条数--"+result);
    }
    /**
     * 将 BuySaleinfosSub 列表转换为 SaleInfo 列表
     */
    private List<SaleInfo> convertToSaleInfoList(List<BuySaleinfosSub> buySaleinfosSubList) {
        List<SaleInfo> result = new ArrayList<>(buySaleinfosSubList.size());

        for (BuySaleinfosSub sub : buySaleinfosSubList) {
            SaleInfo saleInfo = new SaleInfo();
            saleInfo.setSaleInfosId(sub.getSubid());
            saleInfo.setBeginTime(sub.getBeginTime());
            saleInfo.setFirmCode(String.valueOf(sub.getDeptId()));
            saleInfo.setCreateTime(sub.getCreateTime());
            saleInfo.setYear(sub.getYear());
            saleInfo.setBillNoWeight(sub.getBillNoWeight());
            saleInfo.setBillDateWeight(sub.getCreateTime());
            saleInfo.setSampleNumberList(sub.getSampleNumberList().toUpperCase());
            saleInfo.setSampleNumberCount(sub.getSampleNumberCount());
            saleInfo.setDeptId(sub.getDeptId());

            result.add(saleInfo);
        }

        return result;
    }

}
